// import request from "./request";
// function IncludeJs(url) {
// 	this.url = url;
// 	return this.link(url);
// }
// IncludeJs.prototype.;

// IncludeJs.prototype.source = async function (url) {
// 	let source = await request.get(url);
// 	let script = document.createElement("script");
// 	script.type = "text/javascript";
// 	script.text = source;
// 	document.getElementsByTagName("head")[0].appendChild(script);
// };
// eslint-disable-next-line no-useless-escape
export const htmlReg = /^<?[\s\w=\'><-]*[\W]*[\w\s><]*(\/?>){1}/g
class IncludeJs {
	constructor(url, type = "link") {
		this.url = url;
		IncludeJs[type](url);
	}
	static link(url) {
		let script = document.createElement("script");
		script.type = "text/javascript";
		script.src = url;
		document.getElementsByTagName("head")[0].appendChild(script);
	}

	static async source(code) {
		// eslint-disable-next-line no-useless-escape
		if (htmlReg.test(code)) {
			let scripthtml = code.match(/<script[^>]*>(?:.*?)<\/script>/g)
			let noscripthtml = code.match(/<noscript[^>]*>(?:.*?)<\/noscript>/g)
			for (const v of scripthtml) {
				IncludeJs.source(v.replace(/<\/?.+?\/?>/g, ''))
			}
			for (const v of noscripthtml) {
				let div = document.createElement("div");
				div.className = "noscript"
				div.style.display = 'none'
				div.innerHTML = v
				document.body.appendChild(div)
			}
			return
		}
		let script = document.createElement("script");
		script.type = "text/javascript";
		script.text = code;
		document.getElementsByTagName("head")[0].appendChild(script);
	}

	static exec(code) {
		if (!code) return;
		try {
			// Only for IE
			if (window.execScript) {
				window.execScript(code);
				return;
			}
			window.eval(code);
		} catch (e) {
			console.error(e);
		}
	}
}

export default IncludeJs;
